package com.ruoyi.major.service.impl;

import com.ruoyi.common.constant.UserConstants;
import com.ruoyi.common.core.domain.AjaxResult;
import com.ruoyi.common.core.redis.RedisCache;
import com.ruoyi.common.utils.StringUtils;
import com.ruoyi.major.domain.StuMagor;
import com.ruoyi.major.mapper.StuMagorMapper;
import com.ruoyi.major.service.IStuMagorService;
import org.springframework.stereotype.Service;
import org.springframework.web.bind.annotation.ResponseBody;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;


@Service
public class StuMajorServiceImpl implements IStuMagorService {
    @Resource
    private StuMagorMapper stuMagorMapper;


    @Resource
    private RedisCache redisCache;

    @Override
    public List<StuMagor> selectMagorList(StuMagor stuMagor) {
        String key = "major";
        List<StuMagor> majorString = redisCache.getCacheList(key);
        //如果redis中有值，则从redis中获取值
        if (!majorString.isEmpty()){
            return majorString;
        }
        //如果没有则查询数据库并放入redis中去
        List<StuMagor> stuMagors = stuMagorMapper.selectMagor(stuMagor);
        redisCache.setCacheList("major",stuMagors);
//        redisCache.expire("major",30L, TimeUnit.MINUTES);


        return stuMagors;
    }

    @Override
    public int insertMagor(StuMagor stuMagor) {
        return stuMagorMapper.insertMagor(stuMagor);
    }

    @Override
    public String checkMajorNameUnique(StuMagor stuMagor) {
        Long MagId = StringUtils.isNull(stuMagor.getMagId()) ? -1L : stuMagor.getMagId();
        StuMagor info = stuMagorMapper.checkMajorNameUnique(stuMagor.getMagName());
        if (StringUtils.isNotNull(info) && info.getMagId().longValue() != MagId.longValue())
        {
            return UserConstants.NOT_UNIQUE;
        }
        return UserConstants.UNIQUE;
    }

    @Override
    public int updateMagor(StuMagor stuMagor) {
        //更新缓存
        //专业id不能为空
        Long magId = stuMagor.getMagId();
        if (magId == null){
           return 0;
        }
        stuMagorMapper.updateMagor(stuMagor);
        //删除缓存
        redisCache.deleteObject("major");
        return 1;
    }

    @Override
    public StuMagor selectMagorById(Long magId) {
        return stuMagorMapper.selectMagorById(magId);
    }

    @Override
    public int deleteMagorById(Long magId) {
        return stuMagorMapper.deleteMagorById(magId);
    }

    @Override
    public int deleteMagorByIds(Long[] magIds) {
        return stuMagorMapper.deleteMagorByIds(magIds);
    }

    @Override
    public List<StuMagor> selectAllMagorList() {
        return stuMagorMapper.selectAllMagorList();
    }

    @Override
    public List<Long> selectMagorByCourId(Long courId) {
        return stuMagorMapper.selectMagorByCourId(courId);
    }


}
